import React, { PureComponent, Fragment } from 'react';
import { Card, Radio, Button } from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import _ from 'lodash';
import ProjectsPath from '@/components/ProjectsPath';
import AuthorizedButton from '@/components/AuthorizedButton';
import qs from 'qs';
import CurrentStage from '../components/CurrentStage';
import PageEmpty from '@/components/PageEmpty';
import PageTop from './components/PageTop';
import styles from '../../index.less';
import { BaseTable, utils } from '@/components/BaseTable';
import { getTitleTree, getFixedColumns } from './utils/tableUtils';

@connect(state => ({
  items: state.ContractPlanEntireProjectItems,
  orgStructure: state.orgStructure,
  overAllYears: state.ContractPlanEntireProjectItems.overAllYears,
  currentYear: state.ContractPlanEntireProjectItems.currentYear,
  currentMonths: state.ContractPlanEntireProjectItems.currentMonths,
  currentShowGroup: state.ContractPlanEntireProjectItems.currentShowGroup,
}))
export default class PriceManage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      emptyMsg: '',
      scrollRight: false,
      headerHeight: [],
      attributesCheckeds: ['金额', '面积', '套数', '均价'],
      subtractHeight: '165px',
    };
  }

  componentWillMount() {
    this.setState({
      headerHeight: [30, 30, 30, 30, 30],
    });
  }

  componentDidMount() {
    // window.console.log(treeUtils.calculateTreeData(treeData), 'calculateTreeData');
    const { match } = this.props;
    // if :version！=null 获取items
    // 根据 items获取 searchItems
    const projectId = match.params.project;

    this.clearItems();
    this.getItems(this.props);
  }

  componentWillReceiveProps(nextProps) {
    // match变动
    if (
      this.props.match.params.project !== nextProps.match.params.project &&
      nextProps.match.params.project
    ) {
      this.clearItems();
      this.getItems(nextProps);
    }
  }

  onChangeAttributesCheckeds(checkedValues) {
    this.setState({
      attributesCheckeds: checkedValues,
    });
  }

  // 根据高级筛选按钮显示隐藏判断表格的高度
  subtractHeight = expandForm => {
    this.setState({
      subtractHeight: expandForm ? '215px' : '165px',
    });
  };

  clearItems = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanEntireProjectItems/clear',
    });
  };

  getItems = (props, values = '') => {
    this.setState({ emptyMsg: '全盘签约计划数据加载中' });
    const self = this;
    const { dispatch, match } = props;
    const params = {
      projectId: match.params.project,
      code: values,
    };
    dispatch({
      type: 'ContractPlanEntireProjectItems/init',
      payload: {
        params,
      },
      callback: data => {
        if (_.isEmpty(data)) {
          self.setState({ emptyMsg: '暂无全盘签约计划数据' });
        }
      },
    });
  };

  /**
   * @description: 确认供货
   * @param {type}
   * @return
   */
  handleOkSupplyClick = () => {
    // _paq.push(['trackEvent', 'appClick', '<appName>','点击应用' ]);
  };

  /**
   * @description: 导出报表
   * @param {type}
   * @return
   */
  handleExportReportClick = () => {
    const { match } = this.props;
    const params = {
      projectId: match.params.project,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    window.open(
      `${process.env.apiUrl}/api/v1/signPlan/signPlanVersion/overallSignPlanExport?${exportQueryString}`,
    );
  };

  changeCurrentYear(value) {
    const { dispatch } = this.props;
    const year = value.target.value;
    const self = this;
    dispatch({
      type: 'ContractPlanEntireProjectItems/changeCurrentYear',
      payload: {
        currentYear: year,
      },
      callback: () => {
        self.getItems(self.props);
      },
    });
  }

  yearsRender() {
    let node;
    const { overAllYears, currentYear } = this.props.items;
    const { scrollRight } = this.state;
    if (overAllYears.length) {
      node = (
        <div style={!scrollRight ? { position: 'fixed', right: '40px' } : null}>
          <Radio.Group
            onChange={e => this.changeCurrentYear(e)}
            defaultValue={currentYear}
            buttonStyle="solid"
            size="small"
          >
            {overAllYears.map((element, index) => {
              if (index <= 15) {
                return (
                  <Radio.Button key={element} value={element}>
                    {element}
                  </Radio.Button>
                );
              }
            })}
            {overAllYears.length > 15 && <Radio.Button disabled>...</Radio.Button>}
          </Radio.Group>
        </div>
      );
    }
    return node;
  }

  render() {
    const { attributesCheckeds, emptyMsg, scrollRight, headerHeight, subtractHeight } = this.state;
    const treeData = this.props.items.searched;
    const { expandedRowKeys, overAllYears, searchItems } = this.props.items;
    const { currentYear, currentMonths, currentShowGroup } = this.props;
    let titleTree = [];
    let fixedColumns = [];
    if (currentYear && overAllYears.length) {
      titleTree = getTitleTree(currentYear, currentMonths, currentShowGroup);
      fixedColumns = getFixedColumns(currentYear, currentMonths, currentShowGroup);
    }
    const headerRenderer = utils.getHeaderRenderer(titleTree, 4, e => this.yearsRender(e));
    return (
      <PageHeaderWrapper
        className="page-header"
        breadcrumb={null}
        title={<ProjectsPath menu="SupplyPlan" {...this.props} />}
        tags={<CurrentStage {...this.props} />}
        extra={[
          <div key="1" className="header-btns">
            {treeData && treeData.length > 0 ? (
              <AuthorizedButton authority="business_signing_overallExportReport">
                <Button className="yellow-button" onClick={this.handleExportReportClick}>
                  导出报表
                </Button>
              </AuthorizedButton>
            ) : (
              <></>
            )}
          </div>,
        ]}
      >
        <Card className="page-header-card">
          <div className={styles.container}>
            {!_.isEmpty(searchItems) ? (
              <PageTop
                getItems={this.getItems}
                attributesCheckeds={attributesCheckeds}
                onChangeAttributesCheckeds={e => this.onChangeAttributesCheckeds(e)}
                {...this.props}
                expandForm={this.subtractHeight}
                currentYear={currentYear}
              />
            ) : null}
            {treeData.length > 0 && overAllYears.length ? (
              <Fragment>
                <BaseTable
                  subtractHeight={subtractHeight}
                  defaultExpandedRowKeys={expandedRowKeys}
                  expandColumnKey="name"
                  rowKey="signDetailId"
                  fixedColumns={fixedColumns}
                  headerHeight={headerHeight}
                  headerRenderer={headerRenderer}
                  treeData={treeData}
                />
              </Fragment>
            ) : (
              <PageEmpty emptyTitle={emptyMsg} />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
